﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;

namespace LearnWPF.Controls.Helper
{
    public class TextBoxAdorner : Adorner
    {
        private readonly ContentPresenter _contentPresenter;
        private Control Control
        {
            get
            {
                return (Control)this.AdornedElement;
            }
        }


        public TextBoxAdorner(UIElement adornedElement, string watermark) : base(adornedElement)
        {
            this.IsHitTestVisible = false; // should not accept focus or Hit test

            this._contentPresenter = new ContentPresenter
            {
                Content = watermark,
                Opacity = 0.3
            };

            TextElement.SetForeground(_contentPresenter, Brushes.Gray);

            double left = this.Control.Margin.Left + this.Control.Padding.Left + 4.0;
            double top = this.Control.Margin.Top + this.Control.Padding.Top + 3.0;          
            this.Margin = new Thickness(left, top, 0, 0);
          

            if (this.Control is ItemsControl && !(this.Control is ComboBox))
            {
                this._contentPresenter.VerticalAlignment = VerticalAlignment.Center;
                this._contentPresenter.HorizontalAlignment = HorizontalAlignment.Center;
            }

            Binding binding = new Binding("IsVisible")
            {
                Source = adornedElement,
                Converter = new BooleanToVisibilityConverter()
            };
            this.SetBinding(VisibilityProperty, binding);
        }    


        #region Override
      
        protected override int VisualChildrenCount
        {
            get
            {
                return 1;
            }
        }

        protected override Visual GetVisualChild(int index) // replace the Visual of the TextBox with the visual of the _contentPresenter;
        {
            return this._contentPresenter;
        }

        protected override Size MeasureOverride(Size constraint)
        {
            this._contentPresenter.Measure(this.Control.RenderSize); // delegate the measure override to the ContentPresenter's Measure
            return this.Control.RenderSize;
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            this._contentPresenter.Arrange(new Rect(finalSize));
            return finalSize;
        }

        #endregion Override
    }
}
